package com.overlord.im.web.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Throwables;
import com.overlord.im.commons.jwt.JwtUtils;
import com.overlord.im.web.config.WebServerProperty;
import com.overlord.im.web.user.entity.UserEntity;
import com.overlord.im.web.user.mapper.UserEntityMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * All rights Reserved, Designed By www.szy.cn
 *
 * @author wuwei
 * @title UserService
 * @package com.overlord.im.web.user.service
 * @date 2021-03-19 15:32
 * @Copyright 2014-现在 All rights reserved. 厦门神州鹰软件科技有限公司
 */
@Service
@Slf4j
public class UserService extends ServiceImpl<UserEntityMapper, UserEntity> {

    @Resource
    private WebServerProperty webServerProperty;

    /**
     * 登录获取token
     *
     * @param loginName
     * @param passWord
     * @return
     */
    public String login(String loginName, String passWord) {
        UserEntity userEntity =
                getBaseMapper().selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getLoginName,
                        loginName).eq(UserEntity::getPassWord, passWord));
        if (null != userEntity) {
            try {
                return JwtUtils.createJWT(userEntity.getId().toString(), userEntity.getName(),
                        webServerProperty.getJwtTtl());
            } catch (UnsupportedEncodingException e) {
                log.error("encoding error:{}", Throwables.getStackTraceAsString(e));
            }

        }
        return null;
    }
}
